clear();

function parseDom(targetEle) {
    // 解析元素
    var userName = '';
    // console.log(targetEle, 'targetEle');
    var parentEle = targetEle.closest('.item.shadow');
    if (!parentEle) return null;
    // console.log(parentEle, 'parentEle');
    userName = parentEle.querySelector('.user-popover-box .username').innerText;
    // console.log(userName);
    var data = {
        userName
    };
    return data;
}

document.onmousedown = function (e) {
    // 存储解析出来的用户信息
    var e = e || window.event;
    const data = parseDom(e.target);
    window.currentBlockData = data;
}

function addBlacklist() {
    var all = document.querySelectorAll('.pin-list-view .pin-list-wrap ul li');
    // console.log(window.currentBlockData, 'window.currentBlockData');
    var iName = window.currentBlockData.userName;
    for (let index = 0; index < all.length; index++) {
        const element = all[index];
        var userEle = element.querySelector('.user-popover-box .username');
        if (userEle && userEle.innerText && userEle.innerText === window.currentBlockData.userName) {
            // console.log('存入黑名单，移除dom元素');
            let nameList = [];
            chrome.storage.local.get(['nameList'], function (result) {
                nameList = result.nameList ? JSON.parse(result.nameList) : [];
                if(!iName || nameList.includes(iName)) {
                    return;
                };
                nameList.push(iName);
                chrome.storage.local.set({ 'nameList': JSON.stringify(nameList) }, function () {
                    clear();
                });
            });
        }
    }
}

function clear() {
    chrome.storage.local.get(['nameList'], function (result) {
        // console.log(result);
        $(document).ready(function () {
            nameList = result.nameList ? JSON.parse(result.nameList) : [];
            setTimeout(() => {
                var list = Array.from(document.querySelectorAll('.pin-list .item.shadow'));
                list && list.forEach(item => {
                    let username = $(item).find('.pin-header-content .username').text();
                    if (nameList.indexOf(username) !== -1) {
                        $(item).hide();
                    }
                })
            }, 200)
        })
    });
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.cmd == 'test') {
        clear();
    } else if (request.type === 'user') {
        // 屏蔽用户
        addBlacklist();
    }

    console.log(request);
    sendResponse('我收到了你的消息！');
});
